package com.dyw.crashcatch;

import android.app.Application;
import android.util.Log;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class CrashFileUtil {
    private static CrashFileUtil instance;

    private CrashFileUtil() {
    }

    private static final String NATIVE_CRASH = "native_crash";
    private static final String JAVA_CRASH = "java_crash";
    private Application mApplication;

    public static CrashFileUtil getInstance() {
        if (instance == null) {
            instance = new CrashFileUtil();
        }
        return instance;
    }

    public void init(Application application) {
        this.mApplication = application;
        initNativeCrash();
        initJavaCrash();
    }

    private void initNativeCrash() {
        File file = new File(mApplication.getCacheDir(), NATIVE_CRASH);
        if (!file.exists()) {
            file.mkdirs();
            Log.i("TAG", "initNativeCrash: ");
        }
        NativeCrash.initNativeCrash(file.getAbsolutePath());
    }

    private void initJavaCrash() {
        File file = new File(mApplication.getCacheDir(), JAVA_CRASH);
        if (!file.exists()) {
            file.mkdirs();
            Log.i("TAG", "initNativeCrash: ");
        }
        JavaCrash.init(file.getAbsolutePath());
    }

    public List<File> getNativeCrashFiles() {
        File file = new File(mApplication.getCacheDir(), NATIVE_CRASH);
        if (file.exists() && file.isDirectory()) {
            return Arrays.asList(file.listFiles());
        }
        return null;
    }

    public List<File> getJavaCrashFiles() {
        File file = new File(mApplication.getCacheDir(), JAVA_CRASH);
        if (file.exists() && file.isDirectory()) {
            return Arrays.asList(file.listFiles());
        }
        return null;
    }

    public void deleteCrashFiles() {
        File nativeFile = new File(mApplication.getCacheDir(), NATIVE_CRASH);
        deleteFile(nativeFile);

        File javaFile = new File(mApplication.getCacheDir(), JAVA_CRASH);
        deleteFile(javaFile);
    }

    private void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null && files.length != 0) {
                    for (File file1 : files) {
                        deleteFile(file1);
                    }
                }
            }
        }
    }

}
